package com.kuang.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @ClassName SecretUtils
 * @Description: TODO
 * @Author: NeySun
 * @Create: 2022-10-31 14:46
 * @Version 1.0
 **/
public class SecretUtils {

    //java加密
    public static String encryptUtil(String param) throws Exception {
        String message = param;
        byte[] data   = message.getBytes(StandardCharsets.UTF_8);
        // 128位 = 16 byte 的 key 值
        byte[] key = "1234567890abcdef".getBytes(StandardCharsets.UTF_8);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);  // 初始化加密工具
        byte[] encrypted = cipher.doFinal(data);		// 加密
        String en = Base64.getEncoder().encodeToString(encrypted);
        return en;
    }

    //java解密
    public static String decryptUtil(String param) throws Exception {
        byte[] key = "1234567890abcdef".getBytes(StandardCharsets.UTF_8);
        byte[] decode = Base64.getDecoder().decode(param);
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKey keySpec = new SecretKeySpec(key, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);  // 解密模式
        byte[] bytes = cipher.doFinal(decode);
        String msg  = new String(bytes, StandardCharsets.UTF_8);
        // 输出（正确）：“待加密内容”
        return msg;
    }

}